﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Workflow.ComponentModel;
using Microsoft.Crm.Workflow;
using System.Workflow.ComponentModel.Compiler;
using Microsoft.Crm.Sdk;
using Microsoft.Crm.Sdk.Query;
using Microsoft.Crm.SdkTypeProxy;

namespace CrmContrib.Workflow.Activities.Marketing
{
    [CrmWorkflowActivity("Remove Contact from Marketing List", "CrmContrib \\ Marketing")]
    public class RemoveContactFromMarketingListActivity : Activity
    {
        [CrmInput("Contact")]
        [CrmReferenceTarget("contact")]
        [ValidationOption(ValidationOption.Required)]
        public Lookup Contact
        {
            get { return (Lookup)base.GetValue(RemoveContactFromMarketingListActivity.ContactProperty); }
            set { base.SetValue(RemoveContactFromMarketingListActivity.ContactProperty, value); }
        }

        public static readonly DependencyProperty ContactProperty = DependencyProperty.Register("Contact", typeof(Lookup), typeof(RemoveContactFromMarketingListActivity));

        [CrmInput("Marketing List")]
        [CrmReferenceTarget("list")]
        [ValidationOption(ValidationOption.Required)]
        public Lookup MarketingList
        {
            get { return (Lookup)GetValue(MarketingListProperty); }
            set { SetValue(MarketingListProperty, value); }
        }

        public static readonly DependencyProperty MarketingListProperty = DependencyProperty.Register("MarketingList", typeof(Lookup), typeof(RemoveContactFromMarketingListActivity));

        protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
        {
            var contextService = executionContext.GetService<IContextService>();
            var workflowContext = contextService.Context;
            var crmService = workflowContext.CreateCrmService();

            var removeRequest = new RemoveMemberListRequest();
            removeRequest.EntityId = this.Contact.Value;
            removeRequest.ListId = this.MarketingList.Value;

            var addResponse = (RemoveMemberListResponse)crmService.Execute(removeRequest);

            return base.Execute(executionContext);
        }
    }
}
